const jwt = require("../utils/jwt");
const result = require("../utils/result");

const filterRoutes = ["/user"];

module.exports = function jwtMiddleware(req, res, next) {
  const authHeader = req.headers.authorization;

  const isFilterRoute = filterRoutes.some((route) => req.path.includes(route));

  if (isFilterRoute) {
    return next(); // 如果是这些路由，直接跳过JWT验证
  }

  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return res.json(result.fail("未提供有效的 Token"));
  }

  const token = authHeader.split(" ")[1];

  try {
    const decoded = jwt.verifyToken(token);
    console.log(decoded);
    return next();
  } catch (err) {
    return res.json(result.fail("Token 无效或已过期"));
  }
};
